package com.hiedu.controller;

import com.hiedu.beans.dto.ProductAddDTO;
import com.hiedu.beans.dto.ProductUpdateDTO;
import com.hiedu.beans.entity.Product;
import com.hiedu.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController //返回的数据不是页面。，而是数据
@RequestMapping("/api/product") //一级路径
@Slf4j
public class ProductController {
    //调用业务层方法
//自动注入业务对象
    @Autowired
    private ProductService productService;
    @GetMapping("list") // 二级路径
    public Object getProductList(){
        return  productService.getProductList();
    }

    @GetMapping("get")
    public Object getById(){
        Product product = productService.getById();
        return product;
    }

    @GetMapping("{id}")//路径参数，使用路径参数注解来获取值
    public Object getById2(@PathVariable("id") Integer id){
        log.debug("ProductController-getById2-前端传递的商品编号:{}",id);
        Product product = productService.getById2(id);
        return product;
    }

    @DeleteMapping("{id}")
    public Object delete(@PathVariable Integer id){
        productService.delete(id);
        //只要上面的业务代码没有抛出异常
        return "删除商品成功";
    }


//    @PostMapping("add")
//    //@RequestBody 后端接受数据的格式为json
//    public Object add(@RequestBody ProductAddDTO productAddDTO){
//        productService.add(productAddDTO);
//        return "新增商品成功";
//    }

    @PostMapping("add")
    //@RequestBody 后端接受数据的格式为json
    public Object add(@Validated @RequestBody ProductAddDTO productAddDTO){
        productService.add(productAddDTO);
        return "新增商品成功";
    }

    @PutMapping("update")
    public Object update(@RequestBody ProductUpdateDTO productUpdateDTO){
        productService.update(productUpdateDTO);
        return "修改商品成功";
    }


}
